/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller.insert;

import hibernate.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
 *
 * @author Felipe
 */
public class InsertController {
    
    private InsertListener mInsertListener = null;
    
    public InsertController() {
        this(null);
    }
    
    public InsertController(InsertListener pInsertListener) {
        mInsertListener = pInsertListener;
    }
    
    public void setUpdateListener(InsertListener pInsertListener) {
        mInsertListener = pInsertListener;
    }  
    
    public void insert(Object object) {
        Session session = null;
        try {
            SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
            session = sessionFactory.openSession();
            session.beginTransaction();   
            session.save(object);
            session.getTransaction().commit();
            if (mInsertListener != null)
                mInsertListener.onInsertComplete();
        } catch (Exception e) {
            e.printStackTrace();
            if (mInsertListener != null)
                mInsertListener.onInsertError(e);            
        } finally {
            session.flush();
            session.close();            
        }        
    }
    
    public interface InsertListener {
        
        public void onInsertComplete();
        
        public void onInsertError(Exception e);      
        
    };
    
}